package cn.itcast.bos.web.action.base;

import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;


@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area>{

	
	//抽取到BaseAction<Area>
/*	//模型驱动
	private Area area = new Area();
	
	
	@Override
	public Area getModel() {
		// TODO Auto-generated method stub
		return area;
	}
	*/
	//注入业务层对象
	@Autowired
	private AreaService areaService; 
	
	//接受上传文件
	
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}
	
	private String fileFileName;
	
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	//批量导入
	@Action(value="area_batchImport")
	public String batchImport() throws Exception{
		
		//编写解析代码逻辑
		List<Area> areas = new ArrayList<Area>();
		//1加载Excel文件对象
//		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		Workbook workbook = null;
		if(fileFileName.matches("^.+\\.(?i)(xls)$")){
			workbook = new HSSFWorkbook(new FileInputStream(file));//xls后缀
		}else if(fileFileName.matches("^.+\\.(?i)(xlsx)$")){
			workbook = new XSSFWorkbook(new FileInputStream(file));//
		}
		// 2、加载第一个sheet页
		Sheet sheet = workbook.getSheetAt(0);
		
		//读取一个sheet
//		HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
		//读取sheet中的每一行
		for (Row row : sheet) {
			//一行数据对应一个区域
			if(row.getRowNum() == 0){
				//第一行跳过
				continue;
			}//空行调跳过
			if(row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			//基于Pinyin4j生成城市编码和简码
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			province.substring(0, province.length()-1);
			city.substring(0, city.length()-1);
			district.substring(0, district.length()-1);
			//简码
			String[] headArray = PinYin4jUtils.getHeadByString(province+city+district);
			StringBuffer buffer = new StringBuffer();
			for (String  headStr: headArray) {
				buffer.append(headStr);
			}
			String shortcode = buffer.toString();
			area.setCitycode(shortcode);
			//城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city,"");
			area.setCitycode(citycode);
			areas.add(area);
			
		}
		//调用业务层
		areaService.saveBatch(areas);
		
		return NONE;
	}
	
	//条件查询
	@Action(value ="area_pageQuery", results = {@Result(name="success", type="json")})
	public String pageQuery(){
		//构造分页查询对象
		Pageable pageable =new PageRequest(page-1, rows);
		//构造条件查询对象
		Specification<Area> specification = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				//创建保存条件集合对象
				List<Predicate> list = new ArrayList<Predicate>();
				//添加条件
				if(StringUtils.isNoneBlank(model.getProvince())){
					//根据省分查询
					Predicate p1 = cb.like(root.get("province").as(String.class),
							"%"+model.getProvince()+"%");
					list.add(p1);
					
				}
				if(StringUtils.isNoneBlank(model.getCity())){
					//根据省分查询
					Predicate p1 = cb.like(root.get("city").as(String.class),
							"%"+model.getProvince()+"%");
					list.add(p1);
					
				}
				if(StringUtils.isNoneBlank(model.getDistrict())){
					//根据省分查询
					Predicate p1 = cb.like(root.get("district").as(String.class),
							"%"+model.getProvince()+"%");
					list.add(p1);
					
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		//调用业务层，完成查询
		Page<Area> pageData = areaService.findPageData(specification,pageable);
		
		//压入值栈
		ActionContext.getContext().getValueStack().push(pageData);
		
		return SUCCESS;
		
	}
	

}
